package com.zxy.cust;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.ider.deskcust.DeskConstant;
import com.ider.deskcust.IDeskService;
import com.ider.deskcust.PageEntry;
import org.json.JSONException;
import org.json.JSONObject;


public class DeskService extends Service {
    private static String TAG = "zhao";

    private IDeskService service;
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        IDeskServiceImpl service = new IDeskServiceImpl();
        this.service = service;
        return service;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }



    class IDeskServiceImpl extends IDeskService.Stub {
        public IDeskServiceImpl() {
            super();
        }

        @Override
        public void basicTypes(int i, long l, boolean b, float v, double v1, String s) throws RemoteException {

        }


        @Override
        public void loadPageDetail(String detailurl) throws RemoteException {
        }

        @Override
        public void loadPages(String url) throws RemoteException {
            Log.i(TAG, "loadPages: url=="+url);
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPostExecute(String s) {
                    Intent intent = new Intent();
                    intent.setAction(DeskConstant.ACTION_UPDATE_PAGE_COUNT);
                    if(s == null) {
                        intent.putExtra(DeskConstant.PAGE_COUNT_STATE, false);
                        sendBroadcast(intent);
                        return;
                    }
                    try{
                        JSONObject object = new JSONObject(s);
                        Log.i(TAG, "onPostExecute: objectString=="+s);
                        PageEntry pageEntry = new PageEntry(object);
                        intent.putExtra(DeskConstant.PAGE_COUNT_STATE, true);
                        intent.putExtra(DeskConstant.PAGE_DETAIL_ENTRIES, pageEntry);
                        intent.putExtra(DeskConstant.PAGE_DETAIL_PAGES,s);
                        sendBroadcast(intent);
                    } catch (JSONException e) {
                        intent.putExtra(DeskConstant.PAGE_COUNT_STATE, false);
                        sendBroadcast(intent);
                    }
                }

                @Override
                protected String doInBackground(String... strings) {
                    try{
                        return OKhttpManager.exuteFromServer(strings[0]);
                    } catch (Exception e) {
                        return null;
                    }
                }
            }.execute(url);
        }
    }
}
